<template>
  <div class="page-wrapper">
    <div style="text-align: left; margin-bottom: 10px;">
      <span style="display: inline-block; margin-right: 10px;">选择时间:</span>
      <el-date-picker
        v-model="date"
        type="date"
        placeholder="选择日期"
        :picker-options="pickerOptions"
        format="yyyy-M-d"
        value-format="yyyy-M-d"
        size="mini"
        @change="dateChange"
      ></el-date-picker>
    </div>
    <div class="container">
      <c-box title="设备分布图" class="item-1">
        <load-data-wrapper :status="status1">
          <echart-wrapper :click-handle="clickHandle" :option="option1"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box title="累计损耗电量及电费" class="item-2">
        <load-data-wrapper :status="status2">
          <echart-wrapper :option="option2"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box title="综合功率损耗变化" class="item-3">
        <load-data-wrapper :status="status3">
          <echart-wrapper :option="option3"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box title="综合损耗功率及电量变化" class="item-4">
        <load-data-wrapper :status="status4">
          <echart-wrapper :option="option4"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box title="电费变化(相间不平衡调整前后)" class="item-5">
        <div class="top">
          <span>相间电费累计节省</span>
          <span class="bar"></span>
          <span>{{ totalFee }}元</span>
        </div>
        <load-data-wrapper :status="status5" style="flex: 1">
          <echart-wrapper :option="option5"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
    </div>
  </div>
</template>

<script>
import { getTransDis, getRealZhgvPower, getRealLossFee } from "@/api/power";
import LoadDataWrapper from "@/components/base/LoadDataWrapper";
import EchartWrapper from "@/components/EchartWrapper";
import {
  getMonthDay,
  parseTime,
  getLastDayOfMonth,
  getLastMonth
} from "@/utils";
import CBox from "@/components/PageCard";
import {
  colors,
  color,
  activeColor,
  textColor,
  legend,
  grid
} from "@/utils/echarts";
const curDate = getLastDayOfMonth(getLastMonth(new Date()));
// const now = new Date();
export default {
  name: "Switcher1",
  components: {
    CBox,
    LoadDataWrapper,
    EchartWrapper
  },
  data() {
    return {
      date: curDate,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > new Date(curDate).getTime();
        }
      },
      pdfs: [],
      curByq: "",
      devName: "",
      realPowers: null,
      realZhgv: null,
      totalFee: 0,

      status1: "loading",
      status2: "loading",
      status3: "loading",
      status4: "loading",
      status5: "loading",
      option1: null,
      option2: null,
      option3: null,
      option4: null,
      option5: null
    };
  },
  computed: {
    comId() {
      return this.$store.getters.comId;
    }
  },
  async mounted() {
    try {
      const byqData = await getTransDis(this.comId);
      if (byqData.length === 0) {
        this.status1 = "empty";
        this.status2 = "empty";
        this.status3 = "empty";
        this.status4 = "empty";
        this.status5 = "empty";
        return this.$alert("该公司无相关数据...");
      }
      this.pdfs = byqData;
      for (let i = 0; i < byqData.length; i++) {
        const p = byqData[i];
        if (p.transformers instanceof Array && p.transformers.length > 0) {
          this.curByq = p.id + "-" + p.transformers[0].id;
          this.devName = p.name + "-" + p.transformers[0].name;
          break;
        }
      }
      this.status1 = "load";
      this.setOption1();
      this.setOption2();
      this.setOption3();
      this.setOption4();
      this.setOption5();
    } catch (error) {
      console.error(error);
      this.status1 = "error";
      this.status2 = "error";
      this.status3 = "error";
      this.status4 = "error";
      this.status5 = "error";
    }
  },
  methods: {
    dateChange() {
      this.setOption2();
      this.setOption3();
      this.setOption4();
      this.setOption5();
    },
    setOption1() {
      const [substationId, transformerId] = this.curByq.split("-");
      const isActive = id => {
        return parseInt(substationId) === id;
      };
      const data1 = [],
        data2 = [];

      this.pdfs.forEach(p => {
        const a = isActive(p.id);
        data1.push({
          name: p.name,
          id: p.id,
          value: p.transformers.length,
          itemStyle: {
            color: a ? activeColor : color
          }
        });
        p.transformers.forEach(t => {
          data2.push({
            pdf: p.name,
            pdfId: p.id,
            name: t.name,
            id: t.id,
            value: 1,
            itemStyle: {
              color:
                parseInt(transformerId) === t.id &&
                p.id === parseInt(substationId)
                  ? activeColor
                  : color
            }
          });
        });
      });

      const option = {
        tooltip: {
          formatter: "{a} {b}"
        },
        grid: {
          bottom: 150,
          left: 100,
          right: "10%"
        },
        legend: {
          show: false,
          orient: "vertical",
          top: "middle",
          right: "5%",
          textStyle: {
            color: "#f2f2f2",
            fontSize: 14
          },
          icon: "roundRect"
        },
        series: [
          // 主要展示层的
          {
            radius: ["40%", "60%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            itemStyle: {
              normal: {
                color: color,
                borderColor: "white"
              }
            },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "配电房",
            data: data1
          },
          {
            radius: ["60%", "80%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            itemStyle: {
              normal: {
                color: color,
                borderColor: "white"
              }
            },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "变压器",
            data: data2
          }
        ]
      };
      this.option1 = option;
    },
    async setOption2() {
      try {
        const _data = await this.getRealShFeesAndelec();
        if (_data instanceof Object && _data.fcnt instanceof Object) {
          this.status2 = "load";
          const rp = _data.fcnt;
          const totalNum = parseFloat(rp.sumQunty || 0),
            useNum = parseFloat(rp.xftgCutPwrQunty || 0),
            warnPer = 0.2,
            warnColor = colors[1];
          const option = {
            color: colors,
            tooltip: {
              formatter: "已损耗电量: {c}{b}"
            },
            xAxis: [],
            yAxis: [],
            series: [
              // These series are in the first grid.
              {
                type: "gauge",
                center: ["50%", "60%"], // 默认全局居中
                splitNumber: 5, // 刻度数量
                min: 0,
                max: totalNum,
                startAngle: 210,
                endAngle: -30,
                clockwise: true,
                title: {
                  textStyle: {
                    color: color
                  }
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    width: 20,
                    shadowBlur: 0,
                    color: [[warnPer, color], [1, warnColor]]
                  }
                },
                axisTick: {
                  show: false,
                  lineStyle: {
                    color: color,
                    width: 1
                  }
                },
                splitLine: {
                  show: false,
                  length: -20,
                  lineStyle: {
                    color: color
                  }
                },
                axisLabel: {
                  show: true,
                  distance: -4,
                  textStyle: {
                    color: color,
                    fontSize: 10
                  },
                  formatter: v => Math.ceil(v)
                },
                pointer: {
                  // 仪表盘指针
                  show: true,
                  width: 4
                },
                detail: {
                  show: true,
                  textStyle: {
                    fontSize: 16,
                    textAlign: "center",
                    lineHeight: 24
                  },
                  formatter: () => {
                    return (
                      "已损耗电费：\n" +
                      parseFloat(rp.sumFees).toFixed(2) +
                      "元"
                    );
                  }
                },
                data: [
                  {
                    name: "kw.h",
                    value: useNum
                  }
                ]
              }
            ]
          };
          this.option2 = option;
        } else {
          this.status2 = "empty";
        }
      } catch (e) {
        console.error(e);
        this.status2 = "error";
      }
    },
    async setOption3() {
      try {
        const _data = await this.getRealZhgv();
        if (_data instanceof Object && _data.tr instanceof Array) {
          const tr = _data.tr;
          this.status3 = "load";
          const data = [],
            xData = [],
            data1 = [],
            data2 = [],
            data3 = [];
          const n = getMonthDay(this.date);

          for (let i = 1; i <= n; i++) {
            xData.push(i);
            const a = tr.find(e => parseInt(e.day) === i);
            if (a) {
              data1.push(a.xftgCutPwrLoss);
              data2.push(a.yuanVLPRatio);
              data3.push(a.mdfdVLPRatio);
            } else {
              data1.push(null);
              data2.push(null);
              data3.push(null);
            }
          }
          data.push({
            name: "削峰填谷降低综合功率损耗",
            type: "bar",
            data: data1,
            barCategoryGap: "50%"
          });
          data.push({
            name: "原峰谷视在差",
            type: "line",
            data: data2,
            yAxisIndex: 1
          });
          data.push({
            name: "调整后视在差",
            type: "line",
            data: data3,
            yAxisIndex: 1
          });
          const option = {
            color: colors,
            textStyle: textColor,
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "cross"
              }
            },
            legend: {
              ...legend,
              right: 100
            },
            grid,
            xAxis: [
              {
                type: "category",
                data: xData,
                axisLine: {
                  lineStyle: {
                    color: textColor
                  }
                },
                axisTick: {
                  show: false
                },
                axisPointer: {
                  type: "shadow",
                  label: {
                    color: "#fff"
                  }
                }
              }
            ],
            yAxis: [
              {
                type: "value",
                name: "kw",
                axisLine: {
                  lineStyle: {
                    color: textColor
                  }
                },
                splitLine: { show: false },
                axisPointer: {
                  label: { color: "#fff" }
                }
              },
              {
                type: "value",
                name: "kVA",
                axisLine: {
                  lineStyle: {
                    color: textColor
                  }
                },
                axisPointer: {
                  label: { color: "#fff" }
                },
                splitLine: { show: false }
              }
            ],
            series: data
          };
          // this.echarts3.setOption(option);
          this.option3 = option;
        } else {
          this.status3 = "empty";
        }
      } catch (e) {
        console.error(e);
        this.status3 = "error";
      }
    },
    async setOption4() {
      const date = new Date(this.date);
      const [substationId, transformerId] = this.curByq.split("-");
      const post = {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
        substationId,
        transformerId
      };
      this.comId && (post.id = this.comId);
      let max = 0;
      const xData = [],
        data = [],
        yAxis = [];

      try {
        const res = await getRealZhgvPower(post);
        if (res instanceof Array) {
          this.status4 = "load";
          res.forEach(v => {
            let name,
              len = 0;
            const _data = [];
            for (let count = 1; v["value" + count] !== undefined; count++) {
              len++;
              _data.push(v["value" + count]);
            }
            if (v.type1 === "SanLossEnergy") {
              name = "相间电量节省(kw.h)";
              data.push({
                name: name,
                type: "bar",
                data: _data
              });
              yAxis.push({
                type: "value",
                splitLine: {
                  show: false
                }
              });
            } else if (v.type1 === "SanLossFee") {
              name = "相间综合功率损耗节省(kw)";
              data.push({
                name: name,
                yAxisIndex: 1,
                type: "bar",
                data: _data
              });
              yAxis.push({
                type: "value",
                show: false
              });
            } else {
              data.push({
                name: v.type1,
                type: "line",
                yAxisIndex: 2,
                data: _data
              });
              yAxis.push({
                type: "value",
                splitLine: {
                  show: false
                }
              });
            }
            max = Math.max(len, max);
          });
        } else {
          this.status4 = "empty";
        }
      } catch (e) {
        this.status4 = "error";
        console.error(e);
        return;
      }

      const d = new Date(this.date);
      d.setHours(0);
      d.setMinutes(0);
      d.setSeconds(0);
      let t = d.getTime();
      for (let i = 0; i < max; i++) {
        const s = parseTime(t, "{h}:{i}");
        xData.push(s);
        t = t + 15 * 60 * 1000;
      }
      yAxis.push({
        type: "value",
        splitLine: {
          show: false
        }
      });
      const option = {
        color: colors,
        grid: {
          ...grid,
          bottom: 50
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999"
            }
          }
        },
        legend,
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 20
          }
        ],
        xAxis: [
          {
            type: "category",
            data: xData,
            axisPointer: {
              type: "shadow"
            }
          }
        ],
        yAxis: yAxis,
        series: data
      };
      // this.echarts4.setOption(option);
      this.option4 = option;
    },
    async setOption5() {
      const date = new Date(this.date);
      const [substationId, transformerId] = this.curByq.split("-");
      const post = {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        substationId,
        transformerId,
        id: this.comId
      };
      const data = [],
        xData = [];
      let totalFees = 0;
      try {
        const _data = await getRealLossFee(post);
        if (_data instanceof Array) {
          this.status5 = "load";
          _data.forEach(v => {
            totalFees += parseFloat(v.valueSum) || 0;
            xData.push(v.dayVal);
            data.push(v.valueSum);
          });
          this.totalFee = totalFees.toFixed(2);
        } else {
          this.status5 = "empty";
        }
      } catch (e) {
        this.status5 = "error";
        console.error(e);
        return;
      }
      const option = {
        legend: { show: false },
        color: colors,
        grid,
        tooltip: {},
        xAxis: {
          data: xData,
          silent: false,
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name: "元",
          splitLine: { show: false }
        },
        series: [
          {
            name: "电费节省",
            type: "bar",
            data: data,
            barWidth: 14
          }
        ]
      };
      // this.echarts5.setOption(option);
      this.option5 = option;
    },
    async getRealShFeesAndelec() {
      const date = new Date(this.date),
        [substationId, transformerId] = this.curByq.split("-"),
        post = {
          year: date.getFullYear(),
          month: date.getMonth() + 1,
          day: date.getDate(),
          id: this.comId,
          substationId,
          transformerId
        },
        res = await this.$axios.post("/eng/tra/realShFeesAndelec", post);
      return res.data;
    },
    async getRealZhgv() {
      const date = new Date(this.date),
        [substationId, transformerId] = this.curByq.split("-"),
        post = {
          year: date.getFullYear(),
          month: date.getMonth() + 1,
          day: date.getDate(),
          id: this.comId,
          substationId,
          transformerId
        },
        res = await this.$axios.post("/eng/tra/realZhgv", post);
      // this.realZhgv = res.data.tr;
      return res.data;
    },
    async clickHandle(p) {
      if (p.seriesIndex === 0) {
        return;
        // this.selectPdf(p.name);
      } else {
        const { name, pdf, pdfId, id } = p.data;
        this.curByq = pdfId + "-" + id;
        this.devName = pdf + "-" + name;
        this.setOption1();
        this.setOption2();
        this.setOption3();
        this.setOption4();
        this.setOption5();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
  .container {
    flex: 1;
    display: grid;
    grid-gap: 10px;
    grid-template-columns: repeat(8, 1fr);
    grid-template-rows: repeat(2, 1fr);
    .item-1,
    .item-2 {
      grid-column-start: span 2;
    }
    .item-3 {
      grid-column-start: span 4;
    }
    .item-4 {
      grid-column-start: span 3;
    }
    .item-5 {
      grid-column-start: span 5;
    }
  }
}
.row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .echarts {
    width: 100%;
    height: 100%;
  }
}

.item-5 {
  /deep/ .card-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    .top {
      padding: 10px 30px;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
      .bar {
        flex: 1;
        margin: 10px;
        background: #008beb;
        height: 10px;
      }
    }
  }
}
</style>
